import { ref, reactive } from 'vue'
import { defineStore } from 'pinia'
import type { UserResult } from '@/api/auth'
import { authApi, codeApi } from '@/api/auth'
export type userType = {
  phone: string
  _id: string
  shop: shopType
}
export type shopType = {
  name: string
  _id: string
}
export type CodeResult = {
  result: boolean
  id?: string
}
export const useUserStore = defineStore('user', () => {
  const token = ref()
  const phone = ref()
  const id = ref()
  const shop = reactive({
    name: '',
    id: ''
  })
  if (localStorage.getItem('token')) {
    token.value = localStorage.getItem('token')!
  }
  function getToken() {
    return token.value
  }
  function setToken(t: string) {
    console.log('setToken', t)
    token.value = t
    localStorage.setItem('token', t)
  }
  function clearToken() {
    token.value = undefined
    localStorage.removeItem('token')
  }
  function setUserInfo(info: userType) {
    console.log('setUserInfo', info)
    phone.value = info.phone
    id.value = info._id
    console.log('setUserInfo---', id.value)

    shop.name = info.shop?.name
    shop.id = info.shop?._id
  }

  function auth() {
    return new Promise<UserResult>((resolve, reject) => {
      authApi()
        .then((data) => {
          if (data && data.status == 200) {
            setUserInfo(data.data)
            resolve(data.data)
          } else {
            reject({
              message: data.message
            })
          }
        })
        .catch((error) => {
          reject({
            error: error,
            message: '未知错误'
          })
        })
    })
  }
  function loginByCode(code: string): Promise<CodeResult> {
    return new Promise<CodeResult>((resolve, reject) => {
      codeApi(code)
        .then((data) => {
          if (data && data.status == 200) {
            if (data.data.phone) {
              setUserInfo(data.data)
              setToken(data.data.token)
              resolve({
                result: true
              })
            } else {
              resolve({
                result: false,
                id: data.data._id
              })
            }
          } else {
            reject({
              message: data.message
            })
          }
        })
        .catch((error) => {
          reject({
            error: error,
            message: '未知错误'
          })
        })
    })
  }

  return {
    phone,
    id,
    shop,
    getToken,
    setToken,
    clearToken,
    setUserInfo,
    auth,
    loginByCode
  }
})
